package module.library.service.impl;


import common.util.DBUtil;
import dao.LibraryDao.BookDao;
import dao.LibraryDao.BookItemDao;
import dao.impl.LibraryDaoImpl.BookDaoImpl;
import dao.impl.LibraryDaoImpl.BookItemDaoImpl;
import common.model.Entity.libraryEntity.Book;
import common.model.Entity.libraryEntity.BookItem;
import common.model.Entity.libraryEntity.enums.BookStatus;
import module.library.service.BookManagementService;
import network.protocol.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * BookManagementService 接口的实现类
 * 负责图书和其副本的管理
 */
public class BookManagementServiceImpl implements BookManagementService {
    private static final Logger logger = LoggerFactory.getLogger(BookManagementServiceImpl.class);


    private final BookDao bookDao = new BookDaoImpl();
    private final BookItemDao bookItemDao = new BookItemDaoImpl();

    // 私有静态常量实例，类加载时初始化
    private final static BookManagementService INSTANCE =new BookManagementServiceImpl();

    // 公开的静态获取方法，提供全局访问点
    public static BookManagementService getInstance() {
        return INSTANCE;
    }
    // 私有构造方法，防止外部创建实例
    private BookManagementServiceImpl() {}

    /**
     * 添加一本新书
     */
    @Override
    public Response<?> addNewBook(String title,String author,String publisher,String isbn,int stock,String category,int available){
        Book newBook = new Book();
        newBook.setTitle(title);
        newBook.setAuthor(author);
        newBook.setPublisher(publisher);
        newBook.setIsbn(isbn);
        newBook.setStock(stock);
        newBook.setCategory(category);
        newBook.setAvailable(available);

        for(int i=0;i<stock;i++){
            BookItem bookItem = new BookItem();
            bookItem.setIsbn(isbn);
            bookItem.setStatus(BookStatus.AVAILABLE);
            bookItem.setAvailable(available);
            bookItem.setInLibrary(stock);
            bookItemDao.save(bookItem);
        }

        if(!bookDao.save(newBook)){
            return Response.error("添加新书失败，稍后再试");
        }
        return Response.success();
    }

    /**
     * 删除图书 在删除某一本图书前，先删除它的所有副本
     * @param
     */
    @Override
    public Response<Boolean> deleteBook(String isbn) {
        List<BookStatus> forbidStatus = Arrays.asList(BookStatus.BORROWED, BookStatus.RESERVED);
        Optional<List<BookItem>> forbidItems = bookItemDao.findByBookIsbnAndStatus(isbn, forbidStatus);

        if (forbidItems.isPresent() && !forbidItems.get().isEmpty()) {
            // 存在不允许删除的复本
            logger.warn("图书仍存在借出或预约复本，无法删除：isbn={}", isbn);
            return Response.error("图书存在借出或预约复本，无法删除");
        }
        else{
            if(!bookDao.deleteByIsbn(isbn)){
                return Response.error("删除图书失败");
            }
        }
        return Response.success();
    }


//    /**
//     * 删除图书复本，用itemId来删除
//     * @param itemId
//     * @return
//     */
//    // TODO 点击删除
//    @Override
//    public Response<Boolean> deleteBookItems(Long itemId) {
//        return true;
//    }

//    /**
//     * 更新图书的基本信息 只更新库存
//     */
//    @Override
//    public Response<?> updateBookInfo(Book book) {
//
//        if (!bookDao.update(book)) {
//            logger.error("更新图书信息失败: id={}", book.getId());
//            return Response.error("更新图书信息失败，请稍后重试");
//        }
//        return Response.success();
//    }



//    @Override
//    public Response<List<Long>> addBookItems(Long bookIsbn) {
//        BookItem newBookItem = new BookItem();
//        newBookItem.setBookId(bookIsbn);
//        newBookItem.setStatus(BookStatus.AVAILABLE);
//
//        Long newItemId = bookItemDao.save_id(newBookItem);
//        if (newItemId == null) {
//            logger.error("添加图书副本失败: bookId={}", bookIsbn);
//            return Response.error("添加图书副本失败，请稍后重试");
//        }
//        return Response.success(List.of(newItemId));
//    }



    @Override
    public Response<?> manageStock(String bookIsbn, int delta) {
        try {
            // 根据 Isbn 查找图书
            Optional<Book> bookOpt = bookDao.findByIsbn(bookIsbn);
            if (!bookOpt.isPresent()) {
                return Response.error("未找到 ISBN 为 " + bookIsbn + " 的图书");
            }

            Book book = bookOpt.get();

            // 更新库存
            int newStock = book.getStock() + delta;
            if (newStock < 0) {
                return Response.error("库存不能为负数");
            }

            // 更新可用数量
            int newAvailable = book.getAvailable() + delta;
            if (newAvailable < 0) {
                return Response.error("可用数量不能为负数");
            }

            // 直接更新库存和可用数量，而不是更新整个对象
            boolean success = bookDao.updateStockAndAvailable(bookIsbn, newStock, newAvailable);

            if (success) {
                logger.info("库存更新成功: isbn={}, 变化量={}, 新库存={}, 新可用数量={}",
                        bookIsbn, delta, newStock, newAvailable);
                return Response.success("库存更新成功");
            } else {
                logger.error("库存更新失败: isbn={}, 变化量={}", bookIsbn, delta);
                return Response.error("库存更新失败");
            }
        } catch (Exception e) {
            logger.error("管理库存失败: isbn={}, delta={}", bookIsbn, delta, e);
            return Response.error("管理库存失败: " + e.getMessage());
        }
    }
}
